from flask import Flask, request, jsonify
from werkzeug.utils import secure_filename
import os
import datetime
import shutil
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 4096 * 1024 * 1024
# 设置用户名和密码
USERNAME = 'sumz'
PASSWORD = 'Sumz'


def authenticate(username, password):
    # 检查用户名和密码是否匹配
    if username == USERNAME and password == PASSWORD:
        return True
    return False


@app.route('/upload', methods=['POST'])
def upload_file():
    # 获取认证信息
    auth = request.authorization
    if not auth or not authenticate(auth.username, auth.password):
        # 返回未认证的错误响应
        return jsonify({'error': 'Unauthorized'}), 401

    # 检查是否上传了文件
    if 'file' not in request.files:
        return jsonify({'error': 'No file provided'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No file selected'}), 400

    # 确保文件名安全
    filename = secure_filename(file.filename)

    # 保存到指定目录
    #UPLOAD_FOLDER = '/var/openebs/local/pvc-c15edebd-ac99-432b-b04e-91eee98c65d8/data/upload'
    UPLOAD_FOLDER = "D:\\JSONData\\H_SCAN\\"
    # 创建日期目录
    current_date = datetime.datetime.now().date()
    date_folder = os.path.join(UPLOAD_FOLDER, current_date.strftime("%Y%m%d"))
    os.makedirs(date_folder, exist_ok=True)

    # 保存文件
    #file.save(filename)
    file_path = os.path.join(date_folder, filename)
    with open(file_path, 'ab') as f:
        shutil.copyfileobj(file, f)
    # file.save(os.path.join(date_folder, filename))

    return jsonify({'message': 'File uploaded successfully'})


if __name__ == "__main__":
    app.run(host='0.0.0.0')
